﻿<!doctype html>
<head> 
	<meta charset="utf-8" />
	<title>Add a 3D model with Threebox</title>
	<script src="../dist/threebox.js" type="text/javascript"></script>
	<link href="../dist/threebox.css" rel="stylesheet" />
	<script src="config.js"></script>
	<script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script>
	<link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" />
	<style>
		body, html {
			width: 100%;
			height: 100%;
			margin: 0;
		}

		#map {
			width: 100%;
			height: 100%;
		}
		#time {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 80px;
			margin-left: auto;
			margin-right: auto;
			min-width: 90%;
		}
		#hour {
			background: rgba(0, 0, 0, 0.5);
			color: #fff;
			position: absolute;
			left: 0px;
			right: 0px;
			bottom: 40px;
			margin-left: auto;
			margin-right: auto;
			max-width: 30%;
			padding: 5px 10px;
			font-size: 18px;
			line-height: 18px;
			border-radius: 3px;
			text-align: center;
		}
	</style>
</head>
<body>
	<div id='map' class='map'></div>
	<input id='time' type='range' min="0" max="86399" />
	<div id="hour" class="mapboxgl-map"></div>

	<script type="module">
		if (!config) console.error("Config not set! Make a copy of 'config_template.js', add in your access token, and save the file as 'config.js'.");

		mapboxgl.accessToken = config.accessToken;

		let styles = {
			day: 'light-v10', 
			night: 'dark-v10'
		}
		let selectedStyle = styles.day;

		var map = (window.map = new mapboxgl.Map({
			container: 'map',
			style: 'mapbox://styles/mapbox/' + selectedStyle,
			zoom: 18,
			center: [148.9819, -35.3981],
			pitch: 60,
			antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
		}));

		window.tb = new Threebox(
			map,
			map.getCanvas().getContext('webgl'),
			{
				realSunlight: true,
				enableSelectingObjects: true,
				enableTooltips: true
			}
		);

		let model;
		// parameters to ensure the model is georeferenced correctly on the map
		var modelOrigin = [148.9819, -35.39847];

		let date = new Date();//new Date(2020, 7, 14, 0, 39); // change this UTC date time to show the shadow view
		let time = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();
		let timeInput = document.getElementById('time');
		timeInput.value = time;
		timeInput.oninput = () => {
			time = +timeInput.value;
			date.setHours(Math.floor(time / 60 / 60));
			date.setMinutes(Math.floor(time / 60) % 60);
			date.setSeconds(time % 60);
			map.triggerRepaint();
		};

		function createCustomLayer(layerName, origin) {
			let model;
			//create the layer
			let customLayer3D = {
				id: layerName,
				type: 'custom',
				renderingMode: '3d',
				onAdd: function (map, gl) {
					// Attribution, no License specified: Model by https://github.com/nasa/
					// https://nasa3d.arc.nasa.gov/detail/jpl-vtad-dsn34
					let options = {
						type: 'gltf', //'gltf'/'mtl'
						obj: './models/radar/34M_17.glb', //model url
						units: 'meters', //units in the default values are always in meters
						scale: 333.22,
						rotation: { x: 90, y: 180, z: 0 }, //default rotation
						anchor: 'center'
					}
					tb.loadObj(options, function (model) {
						model.setCoords(origin);
						model.addTooltip("A radar in the middle of nowhere", true);
						tb.add(model);
						model.castShadow = true;
						tb.lights.dirLight.target = model;
					});

				},
				render: function (gl, matrix) {
					tb.setSunlight(date, origin); //set Sun light for the given datetime and lnglat
					let dupDate = new Date(date.getTime()); // dup the date to avoid modify the original instance
					let dateTZ = new Date(dupDate.toLocaleString("en-US", { timeZone: 'Australia/Sydney' }));
					hour.innerHTML = "Sunlight on date/time: " + dateTZ.toLocaleString();
					changeStyleWithDaylight(date, origin);
					tb.update();
				}
			};
			return customLayer3D;

		};

		let stats;
		import Stats from 'https://threejs.org/examples/jsm/libs/stats.module.js';
		function animate() {
			requestAnimationFrame(animate);
			stats.update();
		}

		map.on('style.load', function () {
			// stats
			stats = new Stats();
			map.getContainer().appendChild(stats.dom);
			animate();

			map.addLayer(createCustomLayer('3d-model', modelOrigin), 'waterway-label');
		});

		function changeStyleWithDaylight(date, origin) {
			let sunTimes = tb.getSunTimes(date, origin);
			if (date >= sunTimes.sunriseEnd && date <= sunTimes.sunsetStart) {
				if (selectedStyle != styles.day) {
					tb.setStyle("mapbox://styles/mapbox/" + styles.day);
					selectedStyle = styles.day;
				}
			} else {
				if (selectedStyle != styles.night) {
					tb.setStyle("mapbox://styles/mapbox/" + styles.night);
					selectedStyle = styles.night;
				}
			}
		}

	</script>
</body>
